package com.kotlin.heimaplayer.net

import com.itheima.player.util.ThreadUtil
import okhttp3.*
import java.io.IOException

class NetManager private constructor(){
    val client by lazy { OkHttpClient() }
    companion object{
        val manager by lazy { NetManager() }
    }
    /**
     * 发送网络请求
     */
    fun <RESPONSE>sendRequest(req:MRequest<RESPONSE>){

        val request = Request.Builder().url(req.url).get().build()
        client.newCall(request).enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                //刷新列表
                ThreadUtil.runOnMainThread(Runnable{
                    req.handler.onError(req.type,e.message)
                })
            }

            override fun onResponse(call: Call, response: Response) {
                val result = response.body?.string()
                val parseResult = req.parseResult(result)
                //刷新列表
                ThreadUtil.runOnMainThread(Runnable{

                    req.handler.onSuccess(req.type,parseResult)


                })
            }

        })
    }
}